from flask import Flask, jsonify, request
import requests

app = Flask(__name__)

# Sidecar服务的地址和端口
SIDECAR_HOST = "http://localhost:18081"
# Spring应用的直接地址
SPRING_APP_DIRECT = "http://localhost:18080"

@app.route('/health')
def health():
    return jsonify({"status": "UP"})

@app.route('/hello')
def hello():
    return jsonify({"message": "Hello, World! from Python"})

@app.route('/api/data', methods=['POST'])
def process_data():
    # 获取请求体中的JSON数据
    data = request.get_json()
    
    # 处理数据
    if data is None:
        return jsonify({"error": "No JSON data provided"}), 400
    
    # 示例：返回处理后的数据
    result = {
        "received": data,
        "processed": True,
        "timestamp": "处理完成"
    }
    
    return jsonify(result)

# 通过Sidecar调用Spring服务的函数
def call_spring_service(service_name, endpoint, method='GET', data=None):
    """
    通过Sidecar调用Spring服务的通用函数
    
    :param service_name: 服务名称，例如 "spring-app"
    :param endpoint: 服务端点，例如 "/"
    :param method: HTTP方法，默认为GET
    :param data: 请求数据，用于POST请求
    :return: 响应数据
    """
    # 通过Sidecar调用Spring服务
    url = f"{SIDECAR_HOST}/{service_name}{endpoint}"
    try:
        if method.upper() == 'GET':
            response = requests.get(url, timeout=5)
        elif method.upper() == 'POST':
            response = requests.post(url, json=data, timeout=5)
        else:
            return {"error": f"不支持的HTTP方法: {method}"}
        
        response.raise_for_status()  # 如果响应状态码不是200，抛出异常
        
        # 尝试解析JSON响应，如果不是JSON则返回文本
        try:
            return response.json()
        except:
            return {"text_response": response.text}
    except requests.exceptions.RequestException as e:
        return {"error": f"调用Spring服务失败: {str(e)}"}

# 直接调用Spring应用的函数
def call_spring_direct(endpoint, method='GET', data=None):
    """
    直接调用Spring应用的函数（不通过Sidecar）
    
    :param endpoint: 服务端点，例如 "/spring/hello"
    :param method: HTTP方法，默认为GET
    :param data: 请求数据，用于POST请求
    :return: 响应数据
    """
    url = f"{SPRING_APP_DIRECT}{endpoint}"
    try:
        if method.upper() == 'GET':
            response = requests.get(url, timeout=5)
        elif method.upper() == 'POST':
            response = requests.post(url, json=data, timeout=5)
        else:
            return {"error": f"不支持的HTTP方法: {method}"}
        
        response.raise_for_status()
        
        try:
            return response.json()
        except:
            return {"text_response": response.text}
    except requests.exceptions.RequestException as e:
        return {"error": f"直接调用Spring应用失败: {str(e)}"}

@app.route('/call-spring')
def call_spring_hello():
    """
    调用Spring-app服务的根接口
    """
    # 尝试通过Sidecar调用Spring应用
    # 注意：根据Gateway配置，我们使用/spring-app/hello而不是/spring-app/spring/hello
    # 因为我们配置了StripPrefix=1，所以/spring-app后面的路径会直接转发到spring-app服务
    sidecar_result = call_spring_service("spring-app", "/spring/hello")
    
    # 同时尝试直接调用Spring应用作为对比
    direct_result = call_spring_direct("/spring/hello")
    
    return jsonify({
        "python_message": "这是来自Python的调用",
        "sidecar_call": {
            "url": f"{SIDECAR_HOST}/spring-app/spring/hello",
            "result": sidecar_result
        },
        "direct_call": {
            "url": f"{SPRING_APP_DIRECT}/spring/hello",
            "result": direct_result
        },
        "debug_info": {
            "sidecar_host": SIDECAR_HOST,
            "spring_app_direct": SPRING_APP_DIRECT,
            "service_name": "spring-app"
        }
    })

@app.route('/call-spring/data', methods=['POST'])
def call_spring_data():
    """
    调用Spring-app服务的数据处理接口
    """
    data = request.get_json()
    if not data:
        return jsonify({"error": "请提供JSON数据"}), 400
        
    result = call_spring_service("spring-app", "/api/process", method="POST", data=data)
    return jsonify({
        "python_processed": True,
        "spring_response": result
    })

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=3000)